<script setup>
	//导入城市选择器
	import {
		EluiChinaAreaDht
	} from 'elui-china-area-dht'
	//导入消息框
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	//导入图标
	import {
		Delete,
		Edit,
		Search,
		Upload,
		Lock,
		Plus
	} from '@element-plus/icons-vue'
	//导入axios
	import axios from 'axios'
	//设置axios基路径
	axios.defaults.baseURL = '/api'
	import {
		onMounted,
		ref,
		watch,
		reactive
	} from 'vue'

	//获取全国地区数据
	const chinaData = new EluiChinaAreaDht.ChinaArea().chinaAreaflat
	const list = ref([]) //表格数据
	const show = ref(false) //控制医院设置对话框的显示和隐藏
	const showForHospital = ref(false) //控制上传医院信息对话框显隐
	const form = ref({}) //表单数据
	const searchForm = ref({ //查询表单数据
		page: 1,
		limit: 10,
		total: 100
	})
	const hospitalForm = reactive({}) //上传医院表单数据
	const ids = ref([]) //复选框选中id
	const isAdd = ref(false) //是否新增
	const formLabelWidth = '100' //统一表单标签宽度ids

	//城市选择器事件处理
	const onChange = (e) => {
		//将省市区编码设置到hospitalForm中
		hospitalForm.provinceCode = chinaData[e[0]].value
		hospitalForm.cityCode = chinaData[e[1]].value
		hospitalForm.districtCode = chinaData[e[2]].value
	}

	//侦听器，检测page和limit的变化
	watch([() => searchForm.value.page, () => searchForm.value.limit], () => {
		getList()
	})


	const getList = () => {
		axios.post('/admin/hosp/page', searchForm.value)
			.then(response => {
				// console.log(response.data)
				list.value = response.data.records
				searchForm.value.total = response.data.total
			})
	}

	//组件挂在后请求API接口获取数据
	onMounted(() => {
		getList()
	})

	//转换状态
	const status = (row, column, cellValue, index) => {
		if (cellValue == 0) {
			return '可用'
		} else {
			return '已锁定'
		}
	}


	//编辑按钮
	const edit = (row) => {
		// console.log('编辑')
		show.value = true //显示编辑对话框    
		form.value = row //数据回显
		isAdd.value = false //不是新增
	}

	const lock = (id) => {
		// console.log('锁定')
		axios.post('/admin/hosp/lock/' + id)
			.then(response => {
				getList()
				ElMessage({
					message: '锁定成功',
					type: 'success',
				}).catch(() => {
					ElMessage.error('锁定失败')
				})
			})
	}

	//修改对话框确定按钮处理器
	const handleAddOrEdit = () => {
		show.value = false //关闭对话框
		if (isAdd.value) { //新增
			//调用后台接口实现数据修改
			axios.post('/admin/hosp', form.value)
				.then(response => {
					getList()
					ElMessage({
						message: '添加成功',
						type: 'success',
					})
				}).catch(() => {
					ElMessage.error('添加失败')
				})
		} else { //编辑
			//调用后台接口实现数据修改
			axios.put('/admin/hosp', form.value)
				.then(response => {
					getList()
					ElMessage({
						message: '修改成功',
						type: 'success',
					})
				}).catch(() => {
					ElMessage.error('修改失败')
				})
		}

	}

	//对话框关闭处理函数
	const handleClose = () => {
		// console.log('对话框已关闭')
		//关闭对话框，重新加载表格
		getList()
	}

	const cancelEvent = () => {
		ElMessage('已取消删除')
	}

	//删除按钮确定事件处理器
	const confirmEvent = (id, index) => {
		//调用后台API实现删除功能
		axios.delete('/admin/hosp/' + id)
			.then(response => {
				getList()
				ElMessage({
					message: '删除成功',
					type: 'success',
				})
			}).catch(() => {
				ElMessage.error('删除失败')
			})
	}

	// 上传医院信息按钮，如果没有上传过打开上传窗口，否则提示已上传过信息
	const upload = (row) => {
		//调用后台接口查询，如果已经上传过信息，不能重复上传
		axios.get('/admin/hos/' + row.hoscode)
			.then(response => {
				if (response.data.code=="601") {
					ElMessage.error(response.data.msg)
					return
				} 	
				hospitalForm.hosname = row.hosname //回显医院名称
				hospitalForm.hoscode = row.hoscode //回显医院编码
				hospitalForm.logoData=''//清空之前上传的logo
				showForHospital.value = true //显示上传医院信息对话框
			})

	}

	//上传医院logo
	//上传前文件格式判断
	const beforeAvatarUpload = (rawFile) => {
		if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png') {
			if (rawFile.size / 1024 / 1024 > 2) {
				ElMessage.error('上传图片不能超过 2MB!')
				return false
			}
		} else {
			ElMessage.error('只支持jpg和png格式图片')
			return false
		}
		return true
	}
	//上传成功显示图片
	const handleAvatarSuccess = (
		response,
		uploadFile
	) => {
		console.log(response)
		console.log(uploadFile)
		// hospitalForm.logoData = URL.createObjectURL(uploadFile.raw!)
		hospitalForm.logoData = response
	}

	// 上传医院信息处理
	const handleAddForHospital = () => {
		axios.post('/admin/hos', hospitalForm)
			.then(response => {
				showForHospital.value = false //显示上传医院信息对话框
				ElMessage({
					message: '上传成功，请前往医院列表查询',
					type: 'success'
				})
			}).catch(() => {
				ElMessage.error('上传失败')
			})
	}

	//新增
	const add = () => {
		show.value = true //显示对话框
		isAdd.value = true //是新增
		form.value = {} //清空表单
	}

	//条件查询
	const search = () => {
		getList()
	}

	//重置按钮
	const resetForm = () => {
		searchForm.value.hosname = ''
		searchForm.value.hoscode = ''
	}


	//复选框选中事件，获取选中的id
	const handleSelectionChange = (selection) => {
		console.log(selection)
		selection.forEach((item) => {
			ids.value.push(item.id)
		})
		console.log(ids.value)
	}
	//批量删除
	const delBatch = () => {
		if (ids.value.length == 0) {
			ElMessage('至少选择一条')
			return
		}

		ElMessageBox.confirm(
				'刪除后数据不可恢复，确定要删除吗？',
				'提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
			.then(() => {
				axios.post('/admin/hosp/delBatch', ids.value)
					.then(response => {
						getList()
						ElMessage({
							message: '删除成功',
							type: 'success',
						})
					}).catch(() => {
						ElMessage.error('删除失败')
					})
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '已取消删除',
				})
			})

	}
</script>

<template>
	<!-- 查询表单 -->
	<el-form :inline="true" :model="searchForm">
		<el-form-item label="医院名称">
			<el-input v-model="searchForm.hosname" placeholder="请输入医院名称" />
		</el-form-item>
		<el-form-item label="医院编码">
			<el-input v-model="searchForm.hoscode" placeholder="请输入医院编码" />
		</el-form-item>
		<el-form-item label="">
			<el-button type="primary" :icon="Search" @click="search">查询</el-button>
			<el-button @click="resetForm()">清空</el-button>

		</el-form-item>
	</el-form>
	<div style="margin-bottom: 10px;">
		<el-button type="danger" @click="delBatch">批量删除</el-button>
		<el-button type="primary" @click="add">添加医院设置</el-button>
	</div>

	<!-- 数据表格 -->
	<el-table :data="list" stripe border style="width: 100%;height: 60%;" @selection-change="handleSelectionChange">
		<el-table-column type="selection" />
		<el-table-column prop="id" label="序号" />
		<el-table-column prop="hosname" label="医院名称" />
		<el-table-column prop="hoscode" label="医院编号" />
		<el-table-column prop="apiUrl" label="地址" show-overflow-tooltip />
		<el-table-column prop="contactsName" label="联系人" />
		<!-- formatter可以自定义内容 -->
		<el-table-column prop="status" label="状态" :formatter="status" />
		<!-- 操作列 -->
		<el-table-column fixed="right" label="操作" width="350">
			<!-- 具名插槽 -->
			<template #default="scope">

				<el-button type="primary" size="small" @click="edit(scope.row)" :icon="Edit">编辑</el-button>
				<el-popconfirm title="你确定要删除吗?" @confirm="confirmEvent(scope.row.id, scope.$index)"
					@cancel="cancelEvent" confirm-button-text="是" cancel-button-text="否">
					<template #reference>
						<el-button type="danger" size="small" :icon="Delete">删除</el-button>
					</template>
				</el-popconfirm>
				<el-button type="danger" size="small" @click="lock(scope.row.id)" :icon="Lock">
					<template v-if="scope.row.status==0">锁定</template>
					<template v-else>解锁</template>
				</el-button>
				<el-button type="primary" size="small" @click="upload(scope.row)" :icon="Upload">上传信息</el-button>
			</template>
		</el-table-column>
	</el-table>
	<br>

	<!-- 分页 -->
	<el-pagination v-model:current-page="searchForm.page" v-model:page-size="searchForm.limit"
		:page-sizes="[5,10, 20, 30, 40]" background layout="total, sizes, prev, pager, next, jumper"
		:total="searchForm.total" />

	<!-- 编辑&新增对话框-->
	<!-- v-model绑定一个布尔值用来显示和隐藏对话框  -->
	<el-dialog v-model="show" title="医院设置信息" width="40%" @close="handleClose" style="padding-right: 30px;">
		<!-- :model绑定表单数据 -->
		<!-- disabled禁用表单内所有组件 -->
		<!-- disabled也可以放在表单元素上，单独禁用这一个表单元素 -->
		<el-form :model="form">
			<!-- :label-width统一标签宽 -->
			<el-form-item v-if="!isAdd" label="id" :label-width="formLabelWidth">
				<!-- v-model绑定input框的值 -->
				<el-input v-model="form.id" readonly />
			</el-form-item>
			<el-form-item label="医院名称" :label-width="formLabelWidth">
				<el-input v-model="form.hosname" />
			</el-form-item>
			<el-form-item label="医院编码" :label-width="formLabelWidth">
				<el-input v-model="form.hoscode" />
			</el-form-item>
			<el-form-item label="api地址" :label-width="formLabelWidth">
				<el-input v-model="form.apiUrl" />
			</el-form-item>
			<el-form-item label="联系人" :label-width="formLabelWidth">
				<el-input v-model="form.contactsName" />
			</el-form-item>
			<el-form-item label="电话" :label-width="formLabelWidth">
				<el-input v-model="form.contactsPhone" />
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="show = false">取消</el-button>
			<el-button type="primary" @click="handleAddOrEdit">保存</el-button>
		</template>
	</el-dialog>



	<!-- 上传医院信息对话框-->
	<!-- v-model绑定一个布尔值用来显示和隐藏对话框  -->
	<el-dialog v-model="showForHospital" title="上传医院信息" width="40%" @close="handleClose" style="padding-right: 30px;">
		<el-form :model="hospitalForm">
			<el-form-item label="医院名称" :label-width="formLabelWidth">
				<el-input v-model="hospitalForm.hosname" readonly />
			</el-form-item>
			<el-form-item label="医院编码" :label-width="formLabelWidth">
				<el-input v-model="hospitalForm.hoscode" readonly />
			</el-form-item>
			<el-form-item label="医院类型" :label-width="formLabelWidth">
				<el-select v-model="hospitalForm.hostype" placeholder="请选择医院类型">
					<el-option label="三级甲等" value="1" />
					<el-option label="三级乙等" value="2" />
					<el-option label="二级甲等" value="3" />
					<el-option label="二级乙等" value="4" />
					<el-option label="一级" value="5" />
				</el-select>
			</el-form-item>
			<el-form-item label="选择城市" :label-width="formLabelWidth">
				<elui-china-area-dht :leave="3" @change="onChange"></elui-china-area-dht>
			</el-form-item>

			<el-form-item label="详细地址" :label-width="formLabelWidth">
				<el-input v-model="hospitalForm.address" />
			</el-form-item>
			<el-form-item label="LOGO" :label-width="formLabelWidth">
				<!-- <el-upload class="avatar-uploader" action="/api/admin/hos/logo" -->
				<el-upload class="avatar-uploader" action="/api/admin/hos/oss"
					:show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
					<img v-if="hospitalForm.logoData" :src="hospitalForm.logoData" class="avatar" />
					<el-icon v-else class="avatar-uploader-icon">
						<Plus />
					</el-icon>
				</el-upload>
			</el-form-item>
			<el-form-item label="简介" :label-width="formLabelWidth">
				<el-input v-model="hospitalForm.intro" />
			</el-form-item>
			<el-form-item label="坐车线路" :label-width="formLabelWidth">
				<el-input v-model="hospitalForm.route" />
			</el-form-item>
			<el-form-item label="预约规则" :label-width="formLabelWidth">
				<el-input v-model="hospitalForm.bookingRule" />
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="showForHospital = false">取消</el-button>
			<el-button type="primary" @click="handleAddForHospital">保存</el-button>
		</template>
	</el-dialog>
</template>

<style scoped>
	.avatar-uploader .avatar {
		width: 100px;
		height: 100px;
		display: block;
	}
</style>

<style>
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 100px;
		height: 100px;
		text-align: center;
	}
</style>